<template>
  <div class="regional-pricing-tab-table">
    <el-table v-table-style ref="tableRef" v-loading="listLoading" header-row-class-name="common-list-table-header__v2" :data="dataList" stripe border>
      <template slot="empty">
        <BaseListForNoData v-show="!listLoading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
      </template>
      <template v-for="column in columns">
        <el-table-column :key="column.fieldName" show-overflow-tooltip :label="column.displayName" :prop="column.fieldName">
          <template slot-scope="scope">
            <template v-if="column.fieldName === 'areaCondition'">{{ areaConditionObj[scope.row.areaCondition] }}</template>
            <template v-else-if="column.fieldName === 'regions'">{{ scope.row.showRegions | areaParams }}</template>
            <template v-else-if="column.fieldName === 'currencyType'">{{ scope.row.currencyType || 'CNY' }}</template>
            <template v-else>
              {{ scope.row[column.fieldName] }}
            </template>
          </template>
        </el-table-column>
      </template>
      <el-table-column fixed="right" :label="$t('common.fields.action.displayName')" width="180">
        <template slot-scope="scope">
          <span class="color-primary pub_btn mr_12" @click="handleClickAdjustPriority(scope.row)">{{ $t('common.base.adjustPriority') }}</span>
          <span class="color-primary pub_btn mr_12" @click="handleClickEdit(scope.row)">{{ $t('common.base.edit') }}</span>
          <span class="color-danger pub_btn" @click="handleClickDelete(scope.row)">{{ $t('common.base.delete') }}</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="regional-pricing-tab-table-footer" v-if="total">
      <p class="total-count">
        <i18n path="common.base.table.totalCount">
          <span place="count">{{ total }}</span>
        </i18n>
      </p>
      <el-pagination background @current-change="handleCurrentChange" :page-size="paginationInfo.pageSize" :current-page="paginationInfo.pageNum" layout="prev, pager, next" :total="total"> </el-pagination>
    </div>

    <!-- 调整区域定价优先级弹框 -->
    <base-modal :show.sync="showPriorityDialog" :title="$t('common.base.adjustPriority')" width="440px" @close="handleClosePriorityDialog">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <el-form-item :label="$t('common.base.adjustPriorityTip')" prop="priority">
          <el-input v-model="ruleForm.priority" type="number" clearable @blur="priorityInputBlur"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="handleClosePriorityDialog">{{ $t('common.base.cancel') }}</el-button>
        <el-button type="primary" @click="handleSubmitPriorityDialog">{{ $t('common.base.confirm') }}</el-button>
      </div>
    </base-modal>
  </div>
</template>
<script>
import { defineComponent, ref, reactive, toRefs, computed } from 'vue';
import i18n from '@src/locales';

import { areaConditionObj } from '@src/modules/servicePrice/components/RegionalPricingTab/fields.js';

export default defineComponent({
  name: 'regional-pricing-tab-table',
  filters: {
    areaParams(val) {
      let ret = val.map(item => {
        const { adCountry, adProvince, adCity, adDist } = item;

        return [adCountry, adProvince, adCity, adDist].filter(Boolean).join(', ');
      });

      return ret.join('；');
    },
  },
  props: {
    columnFields: {
      type: Array,
      default: () => [],
    },
    // 总条数
    totalNumber: {
      type: Number,
      default: 0,
    },
    columnData: {
      type: Array,
      default: () => [],
    },
    queryParams: {
      type: Object,
      default: () => ({}),
    },
  },
  emits: ['handleCurrentChange', 'handleClickEdit', 'handleClickDelete', 'handleSubmitPriorityDialog'],
  setup(props, { emit }) {
    const ruleFormRef = ref();

    let state = reactive({
      columns: props.columnFields,
      showPriorityDialog: false,
      ruleForm: {
        priority: '',
      },
      rules: {
        priority: [
          { required: true, message: i18n.t('common.base.adjustPriorityTip'), trigger: 'blur' },
          {
            pattern: /^[1-9]\d*$/,
            message: i18n.t('task.tip.greaterThanZeroTip1'),
            trigger: 'blur',
          },
        ],
      },
      oldPriority: '',
    });

    const listLoading = computed(() => {
      return props.queryParams?.listLoading || false;
    });

    const paginationInfo = computed(() => {
      return props.queryParams;
    });

    const total = computed(() => {
      return props.totalNumber || 0;
    });

    const dataList = computed(() => {
      return props.columnData || [];
    });

    // 切换分页
    const handleCurrentChange = pN => {
      emit('handleCurrentChange', pN);
    };

    // 点击删除
    const handleClickDelete = row => {
      emit('handleClickDelete', row);
    };

    // 点击编辑
    const handleClickEdit = row => {
      emit('handleClickEdit', row);
    };

    // 点击调整优先级
    const handleClickAdjustPriority = row => {
      state.oldPriority = row;
      state.showPriorityDialog = true;
    };

    // 取消
    const handleClosePriorityDialog = () => {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.resetFields();
      state.showPriorityDialog = false;
    };

    // 确认
    const handleSubmitPriorityDialog = async () => {
      if (!ruleFormRef.value) return;

      await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
          emit('handleSubmitPriorityDialog', state.oldPriority, state.ruleForm.priority);
        } else {
          console.log('error submit!', fields);
        }
      });
    };

    // 失去焦点
    const priorityInputBlur = () => {
      state.ruleForm.priority = Number(state.ruleForm.priority) > Number(total.value) ? total.value + '' : state.ruleForm.priority;
    };

    return {
      ruleFormRef,
      listLoading,
      ...toRefs(state),
      total,
      dataList,
      handleCurrentChange,
      handleClickDelete,
      handleClickEdit,
      handleClickAdjustPriority,
      handleClosePriorityDialog,
      handleSubmitPriorityDialog,
      priorityInputBlur,
      areaConditionObj,
      paginationInfo,
    };
  },
});
</script>
<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 20px !important;
}
.regional-pricing-tab-table {
  .pub_btn {
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
  }
  &-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12px;
    .total-count {
      font-size: 12px;
      margin: 0;
    }
  }
}
</style>